package com.hnx.admin.system.servce.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnx.admin.api.config.ConfigAPI;
import com.hnx.admin.common.redis.core.RedisCore;
import com.hnx.admin.system.core.SysConfigProperties;
import com.hnx.admin.system.dao.conf.ConfigDAO;
import com.hnx.admin.system.dto.conf.SysConfigDTO;
import com.hnx.admin.system.servce.SysConfigService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/*
创建人： 倔强的头发
创建时间：2024/7/11
功能描述:

*/
@Service
@RequiredArgsConstructor
public class SysConfigServiceImpl implements SysConfigService, ConfigAPI {
    private final RedisCore redisCore;
    private final SysConfigProperties sysConfigProperties;
    private final ConfigDAO configDAO;
    @Override
    public boolean selectCaptchaEnabled() {
        try {
            String captchaEnabled = selectConfigByKey(sysConfigProperties.getCaptchaEnabled());
            return StringUtils.isNotBlank(captchaEnabled) &&  Boolean.parseBoolean(captchaEnabled);
        } catch (Exception e) {
            // 异常情况下，默认认为验证码是启用的，以提高安全性
            return true;
        }
    }
    public String selectConfigByKey(String configKey) {
        if (StringUtils.isBlank(configKey) || configKey.trim().length() == 0) {
            throw new IllegalArgumentException("查找的键值不能为空");
        }
        String redisKey = getCacheKey(configKey.trim());
        String configValue = readConfigFromCache(redisKey);
        if (StringUtils.isNotBlank(configValue)) {
            return configValue;
        }
        QueryWrapper<SysConfigDTO> configWrapper = new QueryWrapper<>();
        configWrapper.eq("config_key", configKey);
        SysConfigDTO retConfig = configDAO.selectOne(configWrapper);
        if (Objects.nonNull(retConfig)) {
            if(retConfig.getConfigKey().equals(sysConfigProperties.getBlackIPList()) && StrUtil.isBlank(retConfig.getConfigValue())){
                retConfig.setConfigValue(NO_IP);
            }
            configValue = retConfig.getConfigValue();
             redisCore.setCache(getCacheKey(retConfig.getConfigKey()), retConfig.getConfigValue());
            return configValue;
        }
        return "";
    }
    private String readConfigFromCache(String redisKey) {
        // 从Redis读取配置值
        return redisCore.getCache(redisKey);
    }
}
